package admin

import (
	"context"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/module/admin/adminLogic"
	"grpc.getaway.adminspro.padmins.com/internal/rpc/utils/database"
	"grpc.getaway.adminspro.padmins.com/pkg/config/businessError"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/db"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/utils"
	pbAdmin "grpc.getaway.adminspro.padmins.com/pkg/proto/admin"
)

func (rpc *admin) AdminDel(ctx context.Context, pb *pbAdmin.AdminDelReq) (*pbAdmin.AdminDelResp, error) {
	ids := []interface{}{}
	for _, id := range pb.Id {
		ids = append(ids, id)
	}
	adminIds := []interface{}{}
	authRoleIds := []interface{}{}
	if pb.OperaterId != 0 {
		adminIds = adminLogic.GetChildrenRoleAdminIds(ctx, pb.OperaterId, true)
		authRoleIds = adminLogic.GetRoleIdsByAdminId(ctx, pb.OperaterId)
	} else {
		adminIds = append(adminIds, pb.OperaterId)
	}

	if len(utils.ArrayDiff(ids, adminIds)) > 0 {
		return nil, businessError.ErrorInfoToRpcError(businessError.AdminOperateOtherRoleError)
	}

	Db := database.Db.GetDefaultDb(ctx)

	has, dbErr := Db.Find("select a.admin_id,g.* from admin_role_access a "+
		"join admin_role g on g.id=a.role_id "+
		"where admin_id in (?) and g.id in (?)", ids, authRoleIds)

	if dbErr != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
	}

	if has != nil {
		return nil, businessError.ErrorInfoToRpcError(businessError.AdminOperateSameRoleError)
	}

	rowCount, e := Db.TransactionFunc(func(Db *db.Db) (interface{}, error) {
		adminRowCount, dbErr := Db.Delete("admin", map[string]interface{}{
			"id": ids,
		})

		if dbErr != nil {
			return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
		}

		_, dbErr = Db.Delete("admin_role_access", map[string]interface{}{
			"admin_id": ids,
		})

		if dbErr != nil {
			return nil, businessError.ErrorInfoToRpcError(businessError.DbError(dbErr))
		}

		return adminRowCount, nil
	})

	if e != nil {
		return nil, e
	}

	return &pbAdmin.AdminDelResp{
		RowCount: rowCount.(int64),
	}, nil
}
